<template>
	<view class="order-list-container">
		<!-- 状态筛选 -->
		<view class="status-tabs">
			<view 
				v-for="(tab, index) in statusTabs" 
				:key="index"
				class="status-tab"
				:class="{ active: currentStatus === tab.value }"
				@click="switchStatus(tab.value)"
			>
				{{ tab.label }}
			</view>
		</view>

		<!-- 订单列表 -->
		<view v-if="orders.length > 0" class="order-list">
			<view 
				v-for="order in orders" 
				:key="order.id" 
				class="order-item"
				@click="goToOrderDetail(order.id)"
			>
				<view class="order-header">
					<text class="order-number">订单号：{{ order.order_number }}</text>
					<text class="order-status" :class="getStatusClass(order.status)">
						{{ getStatusText(order.status) }}
					</text>
				</view>

				<view class="order-goods">
					<view 
						v-for="(item, index) in order.items" 
						:key="index" 
						class="goods-item"
					>
						<image :src="item.product_image_url" class="goods-image" mode="aspectFill"></image>
						<view class="goods-info">
							<text class="goods-name">{{ item.product_name }}</text>
							<view class="goods-price-qty">
								<text class="goods-price">¥{{ item.price.toFixed(2) }}</text>
								<text class="goods-qty">x{{ item.quantity }}</text>
							</view>
						</view>
					</view>
				</view>

				<view class="order-footer">
					<view class="order-total">
						<text class="total-label">实付款：</text>
						<text class="total-amount">¥{{ order.payment_amount.toFixed(2) }}</text>
					</view>
					<view class="order-actions">
						<button 
							v-if="order.status === 'pending_payment'" 
							class="action-btn pay-btn"
							@click.stop="goToPay(order)"
						>
							立即支付
						</button>
						<button 
							v-if="order.status === 'pending_payment'" 
							class="action-btn cancel-btn"
							@click.stop="cancelOrder(order)"
						>
							取消订单
						</button>
						<button 
							v-if="order.status === 'processing'" 
							class="action-btn refund-btn"
							@click.stop="requestRefund(order)"
						>
							申请退款
						</button>
						<button 
							v-if="order.status === 'shipped'" 
							class="action-btn confirm-btn"
							@click.stop="confirmReceived(order)"
						>
							确认收货
						</button>
					</view>
				</view>

				<view class="order-time">
					下单时间：{{ formatTime(order.created_at) }}
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view v-else class="empty-state">
			<image :src="pageImages.order_empty_image" class="empty-image"></image>
			<text class="empty-text">暂无订单</text>
			<text class="empty-tip">快去选购心仪的珠宝吧</text>
		</view>

		<!-- 加载更多 -->
		<view v-if="hasMore && orders.length > 0" class="load-more" @click="loadMore">
			<text class="load-more-text">{{ loading ? '加载中...' : '加载更多' }}</text>
		</view>
	</view>
</template>

<script>
import { get, post, put, showLoading, hideLoading } from '@/utils/request.js'
import { getPageImages } from '@/utils/imageConfig.js'

export default {
	data() {
		return {
			// 页面图片配置
			pageImages: {
				order_empty_image: '/static/images/empty-order.png'
			},
			currentStatus: null, // 当前选中的状态
			statusTabs: [
				{ label: '全部', value: null },
				{ label: '待支付', value: 'pending_payment' },
				{ label: '待发货', value: 'processing' },
				{ label: '待收货', value: 'shipped' },
				{ label: '已完成', value: 'completed' },
				{ label: '已取消', value: 'cancelled' },
				{ label: '已退款', value: 'refunded' }
			],
			orders: [],
			page: 1,
			pageSize: 10,
			hasMore: true,
			loading: false
		}
	},
	async onLoad(options) {
		// 如果有传入状态参数，设置默认状态
		if (options.status) {
			this.currentStatus = options.status;
		}
		await this.loadPageImages();
		this.loadOrders(true);
	},
	onShow() {
		// 页面显示时刷新订单列表
		this.loadOrders(true);
	},
	onReachBottom() {
		// 触底加载更多
		if (this.hasMore && !this.loading) {
			this.loadMore();
		}
	},
	onPullDownRefresh() {
		// 下拉刷新
		this.loadOrders(true);
		uni.stopPullDownRefresh();
	},
	methods: {
		// 加载页面图片配置
		async loadPageImages() {
			try {
				const images = await getPageImages('order');

				if (images.order_empty_image) {
					this.pageImages.order_empty_image = images.order_empty_image.url;
				}

				console.log('订单页面图片配置加载完成');
			} catch (error) {
				console.warn('加载页面图片配置失败，使用默认图片:', error);
			}
		},

		// 切换状态
		switchStatus(status) {
			if (this.currentStatus === status) return;
			this.currentStatus = status;
			this.loadOrders(true);
		},

		// 加载订单列表
		async loadOrders(refresh = false) {
			if (this.loading) return;

			try {
				this.loading = true;
				if (refresh) {
					this.page = 1;
					this.hasMore = true;
				}

				const params = {
					page: this.page,
					pageSize: this.pageSize
				};

				if (this.currentStatus) {
					params.status = this.currentStatus;
				}

				const res = await get('/miniapp/orders', params);
				const newOrders = res.data.orders || [];

				if (refresh) {
					this.orders = newOrders;
				} else {
					this.orders = [...this.orders, ...newOrders];
				}

				this.hasMore = newOrders.length === this.pageSize;
				if (!refresh) {
					this.page++;
				}

			} catch (error) {
				console.error('加载订单列表失败:', error);
				uni.showToast({
					title: error.message || '加载失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},

		// 加载更多
		loadMore() {
			if (this.hasMore && !this.loading) {
				this.page++;
				this.loadOrders(false);
			}
		},

		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				'pending_payment': '待支付',
				'processing': '待发货',
				'shipped': '待收货',
				'completed': '已完成',
				'cancelled': '已取消',
				'refunded': '已退款'
			};
			return statusMap[status] || '未知状态';
		},

		// 获取状态样式类
		getStatusClass(status) {
			return `status-${status.replace('_', '-')}`;
		},

		// 格式化时间
		formatTime(timeStr) {
			const date = new Date(timeStr);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hour = String(date.getHours()).padStart(2, '0');
			const minute = String(date.getMinutes()).padStart(2, '0');
			return `${year}-${month}-${day} ${hour}:${minute}`;
		},

		// 跳转到订单详情
		goToOrderDetail(orderId) {
			uni.navigateTo({
				url: `/pages/order/detail?id=${orderId}`
			});
		},

		// 跳转到支付页面
		goToPay(order) {
			uni.navigateTo({
				url: `/pages/order/payment?orderId=${order.id}&orderNumber=${order.order_number}&amount=${order.payment_amount}`
			});
		},

		// 取消订单
		cancelOrder(order) {
			uni.showModal({
				title: '确认取消',
				content: '确定要取消这个订单吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							showLoading('取消中...');
							await put(`/miniapp/orders/${order.id}/cancel`, {});
							uni.showToast({
								title: '订单已取消',
								icon: 'success'
							});
							this.loadOrders(true);
						} catch (error) {
							console.error('取消订单失败:', error);
							uni.showToast({
								title: error.message || '取消失败',
								icon: 'none'
							});
						} finally {
							hideLoading();
						}
					}
				}
			});
		},

		// 申请退款
		requestRefund(order) {
			uni.showModal({
				title: '申请退款',
				content: '确认要申请退款吗？退款将在1-3个工作日内处理完成，金额将退回到您的支付账户。',
				success: async (res) => {
					if (res.confirm) {
						try {
							showLoading('申请中...');
							await post(`/miniapp/orders/${order.id}/refund`, {
								reason: '用户主动申请退款'
							});
							uni.showToast({
								title: '退款申请成功',
								icon: 'success'
							});
							this.loadOrders(true);
						} catch (error) {
							console.error('申请退款失败:', error);
							uni.showToast({
								title: error.message || '申请失败',
								icon: 'none'
							});
						} finally {
							hideLoading();
						}
					}
				}
			});
		},

		// 确认收货
		confirmReceived(order) {
			uni.showModal({
				title: '确认收货',
				content: '确认已收到商品吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							showLoading('确认中...');
							// TODO: 后端需要提供确认收货的接口
							// await post(`/miniapp/orders/${order.id}/confirm-received`, {}, 'PUT');
							uni.showToast({
								title: '确认收货成功',
								icon: 'success'
							});
							this.loadOrders(true);
						} catch (error) {
							console.error('确认收货失败:', error);
							uni.showToast({
								title: error.message || '确认失败',
								icon: 'none'
							});
						} finally {
							hideLoading();
						}
					}
				}
			});
		}
	}
}
</script>

<style scoped>
.order-list-container {
	background-color: #F5F5F5;
	min-height: 100vh;
}

.status-tabs {
	background-color: #FFFFFF;
	display: flex;
	padding: 0 20rpx;
	border-bottom: 1rpx solid #E0E0E0;
}

.status-tab {
	flex: 1;
	text-align: center;
	padding: 30rpx 0;
	font-size: 28rpx;
	color: #666666;
	position: relative;
}

.status-tab.active {
	color: #D4AF37;
	font-weight: bold;
}

.status-tab.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 60rpx;
	height: 4rpx;
	background-color: #D4AF37;
	border-radius: 2rpx;
}

.order-list {
	padding: 20rpx;
}

.order-item {
	background-color: #FFFFFF;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	padding: 30rpx;
}

.order-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
	padding-bottom: 16rpx;
	border-bottom: 1rpx solid #F0F0F0;
}

.order-number {
	font-size: 26rpx;
	color: #666666;
}

.order-status {
	font-size: 26rpx;
	font-weight: bold;
}

.status-pending-payment {
	color: #FF8C00;
}

.status-processing {
	color: #1890FF;
}

.status-shipped {
	color: #52C41A;
}

.status-completed {
	color: #666666;
}

.status-cancelled {
	color: #FF4D4F;
}

.status-refunded {
	color: #FF8C00;
}

.order-goods {
	margin-bottom: 20rpx;
}

.goods-item {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.goods-item:last-child {
	margin-bottom: 0;
}

.goods-image {
	width: 100rpx;
	height: 100rpx;
	border-radius: 8rpx;
	margin-right: 16rpx;
}

.goods-info {
	flex: 1;
}

.goods-name {
	font-size: 28rpx;
	color: #333333;
	margin-bottom: 8rpx;
	display: block;
}

.goods-price-qty {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.goods-price {
	font-size: 28rpx;
	color: #D4AF37;
	font-weight: bold;
}

.goods-qty {
	font-size: 24rpx;
	color: #999999;
}

.order-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.order-total {
	display: flex;
	align-items: center;
}

.total-label {
	font-size: 28rpx;
	color: #666666;
}

.total-amount {
	font-size: 32rpx;
	color: #D4AF37;
	font-weight: bold;
}

.order-actions {
	display: flex;
	gap: 16rpx;
}

.action-btn {
	padding: 12rpx 24rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
	border: 1rpx solid;
	min-width: 120rpx;
}

.pay-btn {
	background-color: #D4AF37;
	color: #FFFFFF;
	border-color: #D4AF37;
}

.cancel-btn {
	background-color: #FFFFFF;
	color: #666666;
	border-color: #E0E0E0;
}

.refund-btn {
	background-color: #FF8C00;
	color: #FFFFFF;
	border-color: #FF8C00;
}

.confirm-btn {
	background-color: #52C41A;
	color: #FFFFFF;
	border-color: #52C41A;
}

.order-time {
	font-size: 24rpx;
	color: #999999;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 40rpx;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 40rpx;
}

.empty-text {
	font-size: 36rpx;
	color: #333333;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.empty-tip {
	font-size: 28rpx;
	color: #999999;
}

.load-more {
	text-align: center;
	padding: 40rpx;
}

.load-more-text {
	font-size: 28rpx;
	color: #666666;
}
</style>
